package com.kede.api.stand.schedu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kede.api.ienum.AppIdTypeEnum;
import com.kede.api.ienum.EnvEnum;
import com.kede.api.stand.domain.WeixTokenDomain;
import com.kede.api.stand.service.WeixTokenService;
import com.kede.api.stand.service.impl.LoginServiceImpl;
import com.kede.api.utils.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author:Pr.li
 * @Date: create in 2023/8/13 17:52
 */
@Component
@EnableScheduling
@Slf4j
public class WxSchedu {

    @Resource
    private LoginServiceImpl loginService;

    @Resource
    private WeixTokenService weixTokenService;


    /**
     *每俩个小时更新 用户端的token
     **/
    @Scheduled(cron = "5 5 0/2 * * *")
    public void reFreshWxToken(){

        EnvEnum env = SpringUtil.getEnv();
        if (!env.equals(EnvEnum.PROD)){
            return;
        }

        LambdaQueryWrapper<WeixTokenDomain> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        queryWrapper.eq(WeixTokenDomain::getType,AppIdTypeEnum.USER_XCX.getType());
        WeixTokenDomain one = weixTokenService.getOne(queryWrapper);
        LoginServiceImpl.TokenEntity tokenEntity = loginService.doGetToken(AppIdTypeEnum.USER_XCX);
        one.setToken(tokenEntity.getAccess_token());
        one.setTime(tokenEntity.getTime());
        one.setUpdateTime(now);
        weixTokenService.updateById(one);
        loginService.getToken(AppIdTypeEnum.USER_XCX);
    }
}
